var sharePage = function (shareinfo) {
};

// APP
if (window.plus) {
    sharePageReady();
} else {
    document.addEventListener('plusready', sharePageReady, false);
}

// Web
$(function () {
    if (AGENT_CLIENT.WEB) {
        sharePageReady();
    }
})

function sharePageReady() {
    var _sharesServices = {};
    var _sharePageModel = null;
    sharePage = function () {
        if (AGENT_CLIENT.APP) {
            this.getShareServices();
        }
        this.init();
        _sharePageModel = this;
    };

    var t1 = new Date().getTime();
    sharePage.prototype = {
        // 初始化
        init: function () {
            if (AGENT_CLIENT.APP) {
                this.paintpage();
            } else {
                this.paintWebPage();
                this.loadBaiduSharePlus();
            }
            this.bindEvent();
        },
        shareInfo: {title: "", content: "", href: "", pic: "", picid: ""},

        // 画web版分享
        paintWebPage: function () {
            var html = [];
            html.push("<div id='sharePage' class='dingwei dingwei1' style='display: none;'><div class='fenxiangbg'><div class='xftubiaok mbbottom overflow'><div class='bdsharebuttonbox'><ul class='gb_resItms'>");
            if(AGENT_CLIENT.APP){
            	html.push("<li><a href='#' class='bds_weixin' data-cmd='weixin'></a>微信好友</li>");
            }
            html.push("<li><a href='#' class='bds_qzone' data-cmd='qzone'></a>QQ空间</li>");
            html.push("<li><a href='#' class='bds_tsina' data-cmd='tsina'></a>新浪微博</li>");
            html.push("</ul></div></div><p class='xfxqx' id='btncancelshare'>取消</p></div></div>");
            $("body").append(html.join(""));
        },

        // 获取分享信息
        getShareInfo: function (cmd, config) {
            var content = _sharePageModel.shareInfo.content ? _sharePageModel.shareInfo.content : "";
            config.bdUrl = _sharePageModel.shareInfo.href;
            config.bdText = _sharePageModel.shareInfo.title + content;
            config.bdPic = _sharePageModel.shareInfo.pic;
            return config;
        },

        // 加载百度分享插件
        loadBaiduSharePlus: function () {
            if (!this.shareInfo) {
                $.alert("分享信息为空！");
                return;
            }

            window._bd_share_config = {
                "common": {
                    onBeforeClick: this.getShareInfo,
                    "bdSnsKey": {},
                    "bdMini": "2",
                    "bdMiniList": false,
                    "bdStyle": "0",
                    "bdSize": "24"
                }, "share": {}
            };
            //插件的JS加载部分
            with (document)0[(getElementsByTagName('head')[0] || body).appendChild(createElement('script')).src = 'http://bdimg.share.baidu.com/static/api/js/share.js?cdnversion=' + ~(-new Date() / 36e5)];
        },

        // 加载商品列表数据
        paintpage: function () {
            var html = [];
            html.push("<div id='sharePage' class='dingwei dingwei1' style='display: none'><div class='fenxiangbg'><div class='xftubiaok mbbottom overflow'>	<p class='xftubiao'  id='shareitem'>");
            html.push("<span tip='weixin'><img src='../../images/wxan.png'/><br/>微信好友</span>");
            html.push("<span tip='weixinp'><img src='../../images/weixin1.png'/><br/>微信朋友圈</span>");
            html.push("<span tip='sinaweibo'><img src='../../images/xlan.png'/><br/>新浪微博</span>");
            html.push("<span tip='qq'><img src='../../images/xlan3.png'/><br/>QQ好友</span>");
            html.push("<span tip='qq'><img src='../../images/kongjian.png'/><br/>QQ空间</span>");
            html.push("<span tip='sms'><img src='../../images/qqan3.png'/><br/>短信</span>");
            html.push("</p></div><p class='xfxqx' id='btncancelshare'>取消</p></div></div>");
            $("body").append(html.join(""));

            var model = this;
            // 分享
            $("#shareitem span").on("click", function () {
                var t2 = new Date().getTime();
                if (t2 - t1 < 1500) {
                    t1 = t2;
                    return;
                } else {
                    t1 = t2;
                }

                if (!model.shareInfo) {
                    $.alert("分享信息为空！");
                    return;
                }
                var shareitem = $(this).attr("tip");

                if (AGENT_CLIENT.APP) {
                    // 短信
                    if ("sms" == shareitem) {
                        model.sendSms();
                        return;
                    }

                    // 分享
                    var ids = {
                        qq: {id: "qq", ex: ""},
                        sinaweibo: {id: "sinaweibo", ex: ""},
                        weixin: {id: "weixin", ex: "WXSceneSession"},
                        weixinp: {id: "weixin", ex: "WXSceneTimeline"}
                    };
                    if (!ids[shareitem]) {
                        return;
                    }

                    // 分享
                    model.shareAction(ids[shareitem].id, ids[shareitem].ex);
                } else {

                }

                model.hide();
            });
        },

        // 绑定事件
        bindEvent: function () {
            var model = this;
            // 取消
            $("#btncancelshare,#sharePage").on("click", function () {
                model.hide();
            });
        },

        // 获取分享服务（app）
        getShareServices: function () {
            plus.share.getServices(function (s) {
                for (var i in s) {
                    var t = s[i];
                    _sharesServices[t.id] = t;
                }
            }, function (e) {
                console.log("获取分享服务列表失败：" + e.message);
            });
        },

        // 分享操作（APP）
        shareAction: function (id, ex) {
            var model = this;
            var s = null;
            if (!id || !(s = _sharesServices[id])) {
                return;
            }
            if (s.authenticated) {
                model.shareMessage(s, ex);
            } else {
                console.log("---未授权---");
                s.authorize(function () {
                    model.shareMessage(s, ex);
                }, function (e) {
                    console.log("认证授权失败：" + e.code + " - " + e.message);
                });
            }
        },

        // 发送分享信息（APP）
        shareMessage: function (shareItem, ex) {
            var sharedata = this.shareInfo;
            var msg = {content: sharedata.content, extra: {scene: ex}};
            console.log(JSON.stringify(sharedata));
            if (true) {
                msg.href = sharedata.href;
                msg.title = sharedata.title ? sharedata.title : " ";
                msg.content = sharedata.content ? sharedata.content : " ";
                if (sharedata.pic) {
                    msg.pictures = [sharedata.pic];
                    msg.thumbs = [sharedata.pic];
                }
            } else {
                if (sharedata.pic) {
                    msg.pictures = [sharedata.pic];
                }
            }

            // 下载并分享
            this.downloadSharePic(shareItem, msg, sharedata.picid);
        },

        // 发送短信（APP）
        sendSms: function () {
            var msg = plus.messaging.createMessage(plus.messaging.TYPE_SMS);
            msg.to = [];
            var content = this.shareInfo.content ? this.shareInfo.content : "";
            msg.body = this.shareInfo.title + ": " + content + "; " + this.shareInfo.href;
            plus.messaging.sendMessage(msg, function () {
                console.log("短信发送成功！")
            }, function (error) {
                console.log("短信发送失败！")
            });
        },

        // 下载分享图片
        downloadSharePic: function (shareItem, msg, picid) {
            if (msg.pictures || msg.pictures.length == 0) {
                msg.pictures.push("http://soolife.com.cn:9091/default.png");
            }
            var filename = (plus.io.PUBLIC_DOWNLOADS + "/share/" + picid + ".jpg");

            // 是否存在
            plus.io.resolveLocalFileSystemURL("_downloads/" + filename, function (entry) {
                    var url = entry.toLocalURL();
                    msg.pictures[0] = url;
                    if (msg.thumbs && msg.thumbs.length > 0) {
                        msg.thumbs[0] = url;
                    }
                    shareItem.send(msg, function () {
                        $.toast("分享到" + shareItem.description + "成功！ ");
                        console.log("分享到\"" + shareItem.description + "\"成功！ ");
                    }, function (e) {
                        console.log("分享到\"" + shareItem.description + "\"失败: " + e.code + " - " + e.message);
                    });
                },
                function (e) {
                    // 下载本地
                    var dtask = plus.downloader.createDownload(msg.pictures[0], {filename: filename}, function (d, status) {
                        // 下载完成
                        if (status == 200) {
                            var url = "file://" + plus.io.convertLocalFileSystemURL(d.filename);
                            msg.pictures[0] = url;
                            if (msg.thumbs && msg.thumbs.length > 0) {
                                msg.thumbs[0] = url;
                            }
                            shareItem.send(msg, function () {
                                console.log("分享到\"" + shareItem.description + "\"成功！ ");
                            }, function (e) {
                                console.log("分享到\"" + shareItem.description + "\"失败: " + e.code + " - " + e.message);
                            });
                        } else {
                            console.log("下载分享图片失败");
                        }
                    });
                    dtask.start();
                });
        },

        // 当前显示状态
        isDisplay: false,

        // 显示
        show: function () {
            t1 = new Date().getTime();
            this.isDisplay = true;
            $("#sharePage").show();
        },
        // 隐藏
        hide: function () {
            this.isDisplay = false;
            $("#sharePage").hide();
        }
    };
}